package com.example.langchaindemo.base;

import com.example.langchaindemo.Const.APIConst;
import com.example.langchaindemo.config.Langchain4jProperties;
import com.example.langchaindemo.service.AiAssistant;
import dev.langchain4j.community.model.dashscope.QwenTokenizer;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.TokenWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 带记忆的聊天
 */
@RequestMapping("/api")
@RestController
@RequiredArgsConstructor
public class ChatWithMemorySample {
    final ChatLanguageModel model;

    final AiAssistant assistant;

    final Langchain4jProperties properties;
    private ChatMemory tokenWindowChatMemory = TokenWindowChatMemory.withMaxTokens(300, new QwenTokenizer(APIConst.instance.QWEN_API_KEY(), APIConst.instance.QWEN_MODEL()));

    @GetMapping("/lowlevel/mem")
    public String lowChat(@RequestParam("message") String message) {
        tokenWindowChatMemory.add(UserMessage.from(message));
        AiMessage answer = model.chat(tokenWindowChatMemory.messages()).aiMessage();
        String answer_text = answer.text(); // Hello Klaus! How can I assist you today?
        tokenWindowChatMemory.add(answer);
        return answer_text;
    }

    @GetMapping("/highlevel/mem")
    public String highChat(@RequestParam("userid") int userId, @RequestParam("message") String message) {
        return assistant.chat(userId, message);
    }
}
